package com.android.plc.ui.manager;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.android.plc.CONST.COMMAND;
import com.android.plc.R;
import com.android.plc.classholder.BasicItem;
import com.android.plc.classholder.BasicItem.Type;
import com.android.plc.classholder.Profile;
import com.android.plc.classholder.ProfileDetail;
import com.android.plc.provider.PLC;
import com.android.plc.provider.PLC.ProfileDetails;
import com.android.plc.provider.PLC.Profiles;
import com.android.plc.ui.dialog.OnWheelSelectListener;
import com.android.plc.ui.dialog.ProfileDetailDialog;
import com.android.plc.util.StringUtil;

public class ProfileManager extends BaseManager<Profile>
{
	private Button mAddProfileDetail;
	private Button mDelProfile;
	private Button mAddProfile;
	private EditText mTxtName;
	private ListView mListProfileDetail;

	public ProfileManager(Context context, ViewGroup view)
	{
		super(context, view, R.layout.add_profile);
	}

	@Override
	public void initView(ViewGroup controlView)
	{
		mDelProfile = (Button) controlView.findViewById(R.id.btn_del_profile);
		mAddProfile = (Button) controlView.findViewById(R.id.btn_add_profile);
		mAddProfileDetail = (Button) controlView.findViewById(R.id.btn_profile_detail);
		mTxtName = (EditText) controlView.findViewById(R.id.editProfileName);
		mListProfileDetail = (ListView) controlView.findViewById(R.id.listProfileDetail);

		mProfileDetailsAdapter = new ProfileDetailsAdapter(mContext);

		mAddProfile.setOnClickListener(this);
		mDelProfile.setOnClickListener(this);
		mAddProfileDetail.setOnClickListener(this);
		mTxtName.addTextChangedListener(this);
		mListProfileDetail.setAdapter(mProfileDetailsAdapter);
	}

	public Uri getUri()
	{
		return PLC.Profiles.CONTENT_URI;
	}

	@Override
	public ContentValues item2maps(Profile profile)
	{
		ContentValues values = new ContentValues();
		values.put(Profiles.NAME, profile.name);
		values.put(Profiles.COMMAND, profile.command);
		return values;
	}

	@Override
	public boolean checkValidity(View view)
	{
		if (mTxtName == null)
			return false;
		if (mTxtName.getText().toString().trim().length() == 0)
		{
			return false;
		}
		return true;
	}

	@Override
	public void displayItem(Profile item)
	{
		if (item == null)
		{
			return;
		}

		if (item.type == Type.ADD_ITEM && item._id == 0)
		{
			mTxtName.setText("");
			mAddProfile.setVisibility(View.GONE);
			mDelProfile.setVisibility(View.GONE);
		} else if (item.type == Type.DEL_ITEM)
		{
			mDelProfile.setVisibility(View.VISIBLE);
		} else if (item.type == Type.NORMAL_ITEM)
		{
			mTxtName.setText(item.name);
			mAddProfile.setVisibility(View.GONE);
			mDelProfile.setVisibility(View.VISIBLE);
		} else if (item.type == Type.ADD_ITEM && item._id != 0)
		{
			mTxtName.setText(item.name);
			mAddProfile.setVisibility(View.GONE);
			mDelProfile.setVisibility(View.VISIBLE);
		}
		mProfileDetailsAdapter.setProfile(item);
	}

	public void afterTextChanged(Editable s)
	{
		Profile profile = getProfile();
		String profileName = mTxtName.getText().toString().trim();
		boolean same = profileName.equals(profile.name);
		if (checkValidity(getView()) && !same)
		{
			profile.name = mTxtName.getText().toString().trim();
			profile.command = 0;
			update(profile);
		}
	}

	public void onClick(View arg0)
	{
		Profile profile = getProfile();
		switch (arg0.getId())
		{
		case R.id.btn_add_profile:
			if (checkValidity(getView()))
			{
				profile.name = mTxtName.getText().toString().trim();
				profile.command = 0;
				insert(profile);
			}
			break;
		case R.id.btn_del_profile:
			if (profile != null)
			{
				delete(profile);
			}
			break;
		case R.id.btn_profile_detail:
			ProfileDetailDialog dialog = new ProfileDetailDialog(mContext);
			dialog.setSelectCodeListener(new OnWheelSelectListener()
			{
				public void onSelected(Object obj)
				{
					ProfileDetail result = (ProfileDetail) obj;
					insertProfileDetail(result);
				}
			});
			dialog.show();
			break;
		default:
			break;
		}

	}

	public void onBasicItemSelected(Manager mgr, BasicItem item, boolean admin)
	{
		if (mgr == Manager.PROFILE)
		{
			Profile profile = (Profile) getProfile();
			displayItem(profile);
		}
	}

	private boolean insertProfileDetail(ProfileDetail detail)
	{
		ContentResolver resolver = mContext.getContentResolver();
		ContentValues values = new ContentValues();
		Profile profile = getProfile();
		if (profile._id == 0)
		{
			String name = mTxtName.getText().toString().trim();
			if (name.length() == 0)
			{
				profile.name = mContext.getString(android.R.string.untitled);
			} else
			{
				profile.name = name;
			}
			insert(profile);
			displayItem(profile);
		}
		values.put(ProfileDetails.PROFILE_ID, profile._id);
		values.put(ProfileDetails.ROOM_UNIT, detail.home_unit);
		values.put(ProfileDetails.COMMAND, detail.command);
		int res_id = -1;
		try
		{
			Uri insertRes = resolver.insert(PLC.ProfileDetails.CONTENT_URI, values);
			String _id = insertRes.getPathSegments().get(1);
			res_id = Integer.valueOf(_id);
		} catch (Exception e)
		{
		} finally
		{
			detail._id = res_id;
		}
		return res_id != -1;
	}

	private ProfileDetailsAdapter mProfileDetailsAdapter;

	private class ProfileDetailsAdapter extends BaseAdapter
	{
		private Context context;
		private Cursor cursor;

		public ProfileDetailsAdapter(Context context)
		{
			super();
			this.context = context;
		}

		final class DetailHolder
		{
			TextView home_unit;
			TextView command;
			Button del;
		}

		private ContentObserver mContentObserver = new ContentObserver(new Handler())
		{
			@Override
			public void onChange(boolean selfChange)
			{
				cursor.requery();
				notifyDataSetChanged();
			}
		};

		public View getView(int position, View convertView, ViewGroup parent)
		{
			// Log.d(TAG, "ProfileDetailsAdapter getView() " + position);
			View view = convertView;
			DetailHolder holder = null;
			if (view == null)
			{
				LayoutInflater factory = LayoutInflater.from(mContext);
				view = factory.inflate(R.layout.profile_detail_item, null);
				holder = new DetailHolder();
				holder.home_unit = (TextView) view.findViewById(R.id.home_unit);
				holder.command = (TextView) view.findViewById(R.id.command);
				holder.del = (Button) view.findViewById(R.id.btn_del_profile);
				holder.del.setOnClickListener(new OnClickListener()
				{
					public void onClick(View v)
					{
						int id = (Integer) v.getTag();
						ContentResolver resolver = context.getContentResolver();
						Uri uri = Uri.withAppendedPath(PLC.ProfileDetails.CONTENT_URI, "" + id);
						resolver.delete(uri, null, null);
					}
				});
				view.setTag(holder);
			} else
			{
				holder = (DetailHolder) view.getTag();
			}
			if (cursor != null && cursor.moveToPosition(position))
			{
				int id_idx = cursor.getColumnIndex(ProfileDetails._ID);
				int home_unit_idx = cursor.getColumnIndex(ProfileDetails.ROOM_UNIT);
				int command_idx = cursor.getColumnIndex(ProfileDetails.COMMAND);
				int command = cursor.getInt(command_idx);
				int homeuint = cursor.getInt(home_unit_idx);
				String cmd;

				String home_unit;
				if (command == COMMAND.ALLUSERLTSON || command == COMMAND.ALLUSERLTSOFF)
				{
					cmd = command == COMMAND.ALLUSERLTSON ? "ON" : "OFF";
					home_unit = mContext.getString(R.string.format_all_room);
				} else if (command == COMMAND.ALLHOMELTSON || command == COMMAND.ALLHOMEUNITOFF)
				{
					cmd = command == COMMAND.ALLHOMELTSON ? "ON" : "OFF";
					home_unit = String.format(mContext.getString(R.string.format_room,
							StringUtil.convCode(homeuint / 16)));
				} else
				{
					cmd = command == COMMAND.ON ? "ON" : "OFF";
					home_unit = StringUtil.convCode(homeuint / 16) + (homeuint % 16 + 1);
				}
				holder.home_unit.setText(home_unit);
				holder.command.setText(cmd);
				holder.del.setTag(cursor.getInt(id_idx));
			}
			return view;
		}

		public long getItemId(int position)
		{
			// Log.d(TAG, "getItemId " + position);
			return position;
		}

		public Object getItem(int position)
		{
			// Log.d(TAG, "getItem " + position);
			return position;
		}

		public int getCount()
		{
			int count = cursor != null ? cursor.getCount() : 0;
			// Log.d(TAG, "Count " + count);
			return count;
		}

		public void setProfile(Profile profile)
		{
			ContentResolver resolver = context.getContentResolver();
			if (profile != null)
			{
				cursor = resolver.query(ProfileDetails.CONTENT_URI, null, ProfileDetails.PROFILE_ID + " = "
						+ profile._id, null, null);
				mProfileDetailsAdapter.notifyDataSetChanged();
			}
			resolver.registerContentObserver(PLC.ProfileDetails.CONTENT_URI, true, mContentObserver);
		}
	};
}
